import paho.mqtt.client as mqtt
from radio import Radio

import json


class RadioMQTT:

    TOPICS = [("radio/action", 0)]

    def __init__(self):
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connected
        self.client.on_message = self.on_message

        self.radio = Radio()

    def on_connected(self, client, userdata, flags, rc):
        self.client.subscribe(RadioMQTT.TOPICS)
        pass

    def on_message(self, client, userdata, msg):
        cmd = msg.payload.decode()
        self.process_command(json.loads(cmd))

    def process_command(self, json_data):
        cmd = json_data["cmd"]
        if cmd == "play":
            data = json_data["data"]
            if data is not None:
                self.radio.play(data)
            else:
                self.radio.resume()
        elif cmd == "pause":
            self.radio.pause()
        elif cmd == "seek":
            data = json_data["data"]
            if data == "up":
                self.radio.seek_station(Radio.SEARCH_UP)
            else:
                self.radio.seek_station(Radio.SEARCH_DOWN)
        else:
            print("known cmd: " + cmd)

    def live_on(self, address, port=1883):
        self.client.connect(address, port=port)
        self.client.loop_forever()


if __name__ == "__main__":
    RadioMQTT().live_on("test.mosquitto.org")
